#!/usr/bin/ruby -w

# http://svnbook.red-bean.com/en/1.4/svn-book.html#svn.reposadmin.create.hooks
# "For security reasons, the Subversion repository executes hook programs
# with an empty environment - that is, no environment variables are set at
# all, not even $PATH".
ENV["PATH"] = "/usr/local/bin:/usr/bin:/bin"

# A Subversion post-commit hook. Edit the configurable stuff below, and
# copy into your repository's hooks/ directory as "post-commit". Don't
# forget to "chmod a+x post-commit".

# You can test this script without checking in bogus revisions with, for example:
# umask 0002
# /home/software/svnroot/terminator/hooks/post-commit "" 1013

# ------------------------------------------------------------------------

# You *WILL* need to change these.

to_address = "software"
reply_to_address = to_address # Use "nil" to reply to the author.

# ------------------------------------------------------------------------

require "cgi"
require "pathname"

# __FILE__ may be relative to the current directory which we're about to change.
salma_hayek = Pathname.new(__FILE__).realpath().dirname()

# We can work out the repository name because we're <path>/<name>/hooks/post-commit
# We could also work this out from the spurious repository_path argument.
repository_path = Pathname.new(__FILE__).parent().parent()
repository_name = repository_path.basename()

require "#{salma_hayek}/lib/build/escaping.rb"
require "#{salma_hayek}/lib/build/patch-to-html-email.rb"

# Subversion's commit-email.pl suggests that svnlook might create files.
Dir.chdir("/tmp")

# What revision in what repository?
ARGV.shift() # throw away the spurious repository_path argument
rev = ARGV.shift()

# Get the overview information.
# svn(1) stores everything as UTF-8 but translates it on output according to LC_CTYPE.
# This appears not to be set by default on jessies.org in the environment in which this job runs.
ENV["LC_CTYPE"] = "en_US.UTF-8"
info = `svnlook info #{repository_path} -r #{rev}`
info_lines = info.split("\n")
author = info_lines.shift()
date = info_lines.shift()
info_lines.shift()
comment = info_lines

# Remove the localized date that follows the ISO date.
date = date.gsub(/ \(.*\)$/, "")

from_address = "#{author}"

subject = "#{repository_name} revision #{rev}"

body = ""

# Output the overview.
body << "<p class=\"revision-header\">#{date} / <b>#{author}</b></p>\n"
body << "<div class=\"check-in-comment\">\n"
body << "<p>"
comment.each() {
    |line|
    body << escapeTextLineToHtml(line)
}
body << "</p></div>\n"

# Get and output the patch.
# We'd like to | #{salma_hayek}/bin/annotate-patch.rb
# But that requires that the correct version of the file is available as trunk/filename
changes = `svnlook diff #{repository_path} -r #{rev}`
changes.gsub!(/\r/, "") # In case we're running on MS Windows.

sendHtmlEmail(from_address, to_address, reply_to_address, subject, body, changes.split("\n"))

# Update the checked-out copy which, in salma-hayek, includes this post-commit trigger.

# FIXME: if there's a script error which prevents us from getting this far, it
# will require manual intervention to fix, because we'll be stuck at the broken
# revision forever.

updateResult = `{ umask 0002 && cd #{salma_hayek}/../#{repository_name} && svn update && make www-dist; } 2>&1`
if $? != 0
    begin
        # Consider using http://www.opengroup.org/onlinepubs/007908799/xcu/mailx.html if sendmail causes a problem.
        sendmail = "/usr/sbin/sendmail"
        
        open("|#{sendmail} #{to_address}", "w") {
            |fd|
            fd.puts("To: #{to_address}")
            fd.puts("Subject: the post-commit update and dist failed")
            fd.puts("\n")
            fd.puts(updateResult)
        }
    rescue Exception => ex
        exit(1)
    end
end

# FIXME: What is the real reason for exit(0)?
exit(0)
